package com.fyzk.activity.gl;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.view.ViewCallBack;
import com.tyjc.unique.net.StringResultBean_New;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.xiangxi.JCOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.NumLotteryOrderDetailActivity;
import com.fyzk.activity.user.xiangxi.OldFootballOrderDetailActivity;
import com.fyzk.activity.zhifu.ZhifuNoLayoutBaseActivity;
import com.fyzk.bean.BetResponse;
import com.fyzk.bean.CurrentPhaseInfo;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.model.UMengTongJi_eventIds;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import http.XRequestCallBack;

public class SSQGLResultActivity extends ZhifuNoLayoutBaseActivity {

    private TopTitleView mTopView;
    private TextView glResult;
    private TextView tiShi_tv;
    private ListView glList;
    String[] arr;
    ArrayList<String> codeList = new ArrayList<String>();
    ArrayList<String> betCodes = new ArrayList<String>();
    private ListAdapter adapter;

    private int total;
    private String betcode;
    private String[] codes;
    private int type_fs;
    private String red_code;
    private String blue_code;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_gllist);

        type_fs = getIntent().getIntExtra("type_fs", 0);
        red_code = getIntent().getStringExtra("red_code");
        blue_code = getIntent().getStringExtra("blue_code");


        mTopView = (TopTitleView) findViewById(R.id.rlTitle);
        mTopView.setOnTitleClickListener(this);
        glResult = (TextView) findViewById(R.id.gl_amount);
        tiShi_tv = (TextView) findViewById(R.id.gl_tishi);
        glList = (ListView) findViewById(R.id.gl_list);

        findCurrentPhase();
        requestGL();

        if (MySharedPreferences.getInstance().getOpenStatus()) {
//            mTopView.setRightVisible(View.VISIBLE);
            mTopView.setRightTxtVisible(View.VISIBLE);
        } else {
            mTopView.setRightTxtVisible(View.GONE);
        }
//
    }

    private void requestGL() {
        showProgressDialog();
        RequestParams params = new RequestParams(UrlDef.GL);
        params.addBodyParameter("lotteryType", LotteryIDUtils.SSQ_LOTTERY_ID_INT + "");
        params.addBodyParameter("play", type_fs + "");
        params.addBodyParameter("code", red_code);
        params.addBodyParameter("appendcode", blue_code);
        sendRequest(HttpMethod.POST, params, 1);
    }


    public void sendRequest(HttpMethod method, RequestParams params, int requestCode) {
        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                onFailure(getRequestCode(), "9999", "网络异常");
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                cancelProgressDialog();
                LogUtil.d("联网：解密后返回>" + result.toString());

                try {
                    StringResultBean_New resultBean = JSON.parseObject(result,
                            StringResultBean_New.class);
                    if ((resultBean.getErrorcode() != null && resultBean.getErrorcode().equals
                            ("0")) || (resultBean.getErrorCode() != null && resultBean
                            .getErrorCode().equals("0"))) {
                        SSQGLResultActivity.this.onSuccess(getRequestCode(), resultBean,
                                result);
                    } else {
                        if (!TextUtil.isEmpty(resultBean.getErrorcode())) {

                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean
                                    .getMsg());
                        } else {
                            onFailure(getRequestCode(), resultBean.getErrorCode(), resultBean
                                    .getMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(getRequestCode(), "9999",
                            result);
                }

            }
        };


        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }

    protected void onFailure(int requestCode, String errorcode, String msg) {
        switch (requestCode) {
            case CommandUtil.FINDCURRENTPHASE:
                break;
            case CommandUtil.USER_COMMON_BETTING:
                cancelProgressDialog();
                break;
        }

    }

    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String result) {
        cancelProgressDialog();
        String value = resultBean.getValue().substring(2, resultBean.getValue().length() - 2);
        LogUtil.v("value>>" + value);
        String values = value.replace("\",\"", "s");
        adapter = new ListAdapter();
        glList.setAdapter(adapter);
        codeList.clear();
        betcode = values;
        codes = betcode.split("s");
        formatData(codes);
        int blueN = codes[0].split("\\+")[1].split(",").length;
        total = codes.length * blueN;
        glResult.setText("过滤后:" + total + "注"
                + total * 2 + "米");

//        Intent intent = new Intent(getContext(), SSQGLResultActivity.class);
//        intent.putExtra("codeValue", values);
//        getActivity().startActivity(intent);
    }


    private void findCurrentPhase() {
        try {
            JSONObject params = new JSONObject();
            params.put("lotteryType", "1001");
            httpPostJson(CommandUtil.FINDCURRENTPHASE, Commands.FINDCURRENTPHASE, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDCURRENTPHASE:
                if (resultBean.getErrorcode().equals("0")) {
                    CurrentPhaseInfo info = JSON.parseObject(resultBean.getData(),
                            CurrentPhaseInfo.class);
                    AppLotteryInfos.setCurrentPrizeInfo(info);
                } else {
                    showToast(resultBean.getMsg());
                }

                break;
            case CommandUtil.USER_COMMON_BETTING:
                if (resultBean.getErrorcode().equals("0")) {
                    final String orderId = JSON.parseObject(resultBean.getData(), BetResponse
                            .class).getOrderid();
                    final String lotteryType = getLotteryId() + "";
                    if (isPartialBet) {
                        mTopView.setRightTxt("继续投注");
                        adapter.notifyDataSetChanged();
                        partialCount++;
                        tiShi_tv.setText("已投 " + partialCount * partialItemCount + " 注，还剩：" + (codeList.size() - partialCount * partialItemCount) +
                                " 注");
                        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("分批投注成功, 是否继续投注")
                                .setPositiveButton
                                        ("是", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                                zhifuAction();

                                            }

                                        }).setNegativeButton("否", new DialogInterface
                                .OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).create().show();
                    } else {

                        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("投注成功")
                                .setPositiveButton
                                        ("查看订单", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                                clear();
                                                Intent intent;
                                                if (lotteryType.contains("30") || lotteryType
                                                        .contains("50")) {
                                                    intent = new Intent(getContext(),
                                                            JCOrderDetailActivity
                                                                    .class);
                                                } else if (lotteryType.contains("40")) {
                                                    intent = new Intent(getContext(),
                                                            OldFootballOrderDetailActivity.class);
                                                } else {
                                                    intent = new Intent(getContext(),
                                                            NumLotteryOrderDetailActivity.class);

                                                }
                                                intent.putExtra(IntentParamUtils.BETDETAILID, orderId);
                                                getContext().startActivity(intent);
                                                SSQGLResultActivity.this.finish();
                                            }

                                        }).setNegativeButton("完成", new DialogInterface
                                .OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                clear();
                                dialog.cancel();
                                setResult(0x6);
                                SSQGLResultActivity.this.finish();
                            }
                        }).create().show();
                    }


                } else {
                    showToast(resultBean.getMsg());
                }
                break;
        }

    }


    private void formatData(String[] arr) {

        for (int i = 0; i < arr.length; i++) {
            String str = arr[i];
            String[] items = str.split("\\+");
            String blue = items[1];
            String[] blueItems = blue.split(",");
            for (int j = 0; j < blueItems.length; j++) {
                StringBuffer item = new StringBuffer();
                item.append("<font color=\"#ff2d19\">");
                item.append(items[0]);
                item.append("</font>+<font color=\"#3720c9\">");
                item.append(blueItems[j]);
                item.append("</font>");
                codeList.add(item.toString());
                betCodes.add(items[0] + "|" + blueItems[j]);
            }

        }

    }

    class ListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return codeList.size();
        }

        @Override
        public Object getItem(int position) {
            return codeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_glresult, null);

                holder.code_tv = convertView.findViewById(R.id.glresult_item_code);
                holder.statue_tv = convertView.findViewById(R.id.glresult_item_statue);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.code_tv.setText(Html.fromHtml(codeList.get(position)));
            if (position < partialCount * partialItemCount) {
                holder.statue_tv.setVisibility(View.VISIBLE);
            } else {
                holder.statue_tv.setVisibility(View.GONE);
            }
            return convertView;
        }

    }

    class ViewHolder {
        TextView code_tv;
        TextView statue_tv;
    }


    @Override
    public String getCodeFilter() {
        return "1";
    }

    int partialCount = 0;
    int partialItemCount = 50;
    int partialZhuShu = 0;

    @Override
    public String getBetCode() {
        StringBuffer sb = new StringBuffer();
        int endIndext = codeList.size() > (partialCount + 1) * partialItemCount ? (partialCount + 1) * partialItemCount : codeList.size();
        for (int i = partialCount * partialItemCount; i < endIndext; i++) {
            String code = betCodes.get(i);
            sb.append(LotteryIDUtils.SSQ_LOTTERY_COMMON_DAN_ID_INT + "-" + code + "^!");
//            if (codes.length == codeList.size()) {
//            } else {
//                sb.append(LotteryIDUtils.SSQ_LOTTERY_COMMON_FU_ID_INT + "-" + code + "^!");
//            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    @Override
    public void onRightClick() {
        super.onRightClick();
        zhifuAction();
    }

    @Override
    public int getZhushu() {
        partialZhuShu = 0;
        int endIndext = codeList.size() > (partialCount + 1) * partialItemCount ? (partialCount + 1) * partialItemCount : codeList.size();
        Log.d(TAG, "getZhushu: codes:" + codeList.size());
        for (int i = partialCount * partialItemCount; i < endIndext; i++) {
            partialZhuShu++;
        }
        Log.d(TAG, "getZhushu: zhushu:" + partialZhuShu);
        return partialZhuShu;
    }

    @Override
    public int getOneAmount() {
        return 2;
    }

    @Override
    public int getLotteryId() {
        return LotteryIDUtils.SSQ_LOTTERY_ID_INT;
    }

    @Override
    public void setLeftMoney() {

    }

    @Override
    protected void clear() {

    }

    @Override
    protected void toXiangQing() {
//		Intent intent = new Intent(getContext(), NumLotteryOrderDetailActivity.class);
//		intent.putExtra(IntentParamUtils.BETDETAILID, responseObj.id);
//		startActivity(intent);
    }

    private void showPartialBetDialog(int count) {
        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("订单超过" + partialItemCount + "单将进行分批投注，本次将投注" + count + "单")
                .setPositiveButton
                        ("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                bet();
                            }

                        }).setNegativeButton("取消", new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create().show();
    }

    @Override
    public void zhifuAction() {
        if (MySharedPreferences.getInstance().getLoginStatus()) {
            if (getZhushu() == 0) {
                lingAert();
            } else {
                UMengTongJi_eventIds.BuyOnClick(this, "认购", "" + lotteryId, AppLotteryInfos.getLotteryName(lotteryId));
                if (yuEisFill()) {
                    if (AppLotteryInfos.getPeriodNew(lotteryId).equals("--")) {
                        showEndTimeDialog("", "--");
                    } else {
                        showSureBuyDialog();
                    }
                } else {
                    showLeftMoneyLowDialog();
                }
            }
        } else {
            AppLotteryInfos.clear();
            ViewCallBack.getInstance().countDownObjs.clear();
            ActivityTaskManager.getInstance().closeAllActivity();
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        }
    }

    boolean isPartialBet = false;

    @Override
    public void showSureBuyDialog() {
        isPartialBet = codeList.size() - partialCount * partialItemCount > partialItemCount;
        if (partialCount == 0 && !isPartialBet) {
            super.showSureBuyDialog();
        } else {
            if (isPartialBet) {
                showPartialBetDialog(partialItemCount);
            } else {
                showPartialBetDialog(codeList.size() - partialCount * partialItemCount);
            }
        }
    }
}
